﻿using System;
using System.Collections.Generic;

namespace WeWork.Service.Framework
{
    /// <summary>
    /// 定时器 类
    /// </summary>
    public class TimerHelper
    {
        /// <summary>
        /// 定时器集合
        /// </summary>
        private static Dictionary<string, System.Timers.Timer> timers = new Dictionary<string, System.Timers.Timer>();

        /// <summary>
        /// settimeout定时器
        /// </summary>
        /// <param name="timerId">定时器ID</param>
        /// <param name="action">触发事件</param>
        /// <param name="interval">触发间隔</param>
        /// <returns></returns>
        public static void SetTimeOut(string timerId, Action action, double interval)
        {
            System.Timers.Timer timer = new System.Timers.Timer(interval);
            timer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                timer.Enabled = false;
                action();
            };
            timer.Enabled = true;
            timers.Add(timerId, timer);
        }

        /// <summary>
        /// 判断是否存在某个ID的定时器
        /// </summary>
        /// <param name="timerId"></param>
        /// <returns></returns>
        public static bool ExistsTimerOut(string timerId)
        {
            bool isExists = false;
            if (timers.ContainsKey(timerId))
            {
                isExists = true;
            }
            return isExists;
        }

        /// <summary>
        /// 销毁定时器
        /// </summary>
        /// <param name="timerId">定时器ID</param>
        public static void ClearTimeOut(string timerId)
        {
            if (ExistsTimerOut(timerId))
            {
                var timer = timers[timerId];
                timer.Enabled = false;
                timer.Close();
                timers.Remove(timerId);
            }
        }

        /// <summary>
        /// 销毁所有定时器
        /// </summary>
        public static void ClearTimeOutAll()
        {
            foreach (var item in timers)
            {
                var timerId = item.Key;
                var timer = timers[timerId];
                timer.Enabled = false;
                timer.Close();
                timers.Remove(timerId);
            }
        }
    }
}